package com.laihuichuxing.mq.consumerRocket;

import com.laihuichuxing.mq.constant.PassengerPostionConst;
import com.laihuichuxing.mq.dao.PositionDao;
import com.laihuichuxing.order.handle.UserHandler4Mongo;
import com.laihuichuxing.pool.UserLbs4MongoPool;
import com.laihuichuxing.pool.dto.UserLbsDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.starter.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.starter.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * Description: 乘客定位消费者
 *
 * @author YangGuang
 * @since: 1.0
 * Create Date Time: 2018/10/10 17:41
 * Update Date Time:
 */
@Slf4j
@Service
@RocketMQMessageListener(topic = "passengerOrderTopic", consumerGroup = "${spring.rocketmq.passengerOrderGroup}")
public class PassengerPositionRConsumer implements RocketMQListener<Map> {

    @Autowired
    private UserHandler4Mongo userHandle;
    @Autowired
    private UserLbs4MongoPool userLbsPool;
    @Autowired
    private PositionDao positionDao;

    /**
     * Description:  保存redis
     *
     * @param longitude   经度
     * @param latitude    纬度
     * @param mobile      手机号
     * @param cityCode    城市code
     * @param userLbsPool userLbsPool
     * @return:
     * @author: YangGuang
     * Create Date Time: 2018/10/10 17:50
     * Update Date Time:
     */
    private UserLbsDto putRedis(String longitude, String latitude, String mobile, String cityCode, UserLbs4MongoPool userLbsPool) {
        UserLbsDto userLbsDto = new UserLbsDto();
        userLbsDto.setPhone(mobile);
        userLbsDto.setCityZone(cityCode);
        userLbsDto.setLatitude(latitude);
        userLbsDto.setLongitude(longitude);
        userLbsDto.setEnable(true);
        userLbsPool.offer(longitude,latitude,mobile,cityCode);
        return userLbsDto;
    }
    /**
     * Description: 乘客下单位置topic
     *
     * @param map
     * @author: YangGuang
     * Create Date Time: 2018/10/10 17:47
     * Update Date Time:
     */
    @Override
    public void onMessage(Map map) {
        try {
            // 获取数据
            String longitude = map.get("longitude").toString();
            String latitude = map.get("latitude").toString();
            String mobile = map.get("mobile").toString();
            String cityCode = map.get("cityCode").toString();
            // 把信息保存到mongo
            UserLbsDto userLbsDto = this.putRedis(longitude, latitude, mobile, cityCode, userLbsPool);
            //匹配司机
            userHandle.task(userLbsDto,1);
            // 持久化到数据库
            positionDao.insertPosition(mobile, longitude, latitude, cityCode, PassengerPostionConst.PASSENGER_ORDER, PassengerPostionConst.PASSENGER_TABLE);
        } catch (Exception e) {
            log.error("乘客下单位置异常:{}", e.toString(), e);
        }
    }
}